<?php
#BEGIN_LICENSE
#-------------------------------------------------------------------------
# Module: CGBlog (c) 2010 by Robert Campbell 
#         (calguy1000@cmsmadesimple.org)
#  An addon module for CMS Made Simple to allow creation, management of
#  and display of blog articles.
# 
#-------------------------------------------------------------------------
# CMS - CMS Made Simple is (c) 2005 by Ted Kulp (wishy@cmsmadesimple.org)
# This project's homepage is: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin 
# section that the site was built with CMS Made simple.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE
if (!isset($gCms)) exit;

$config = $gCms->GetConfig();
$showdraft = 0;
$showall = $this->GetPreference('default_showall',0);
$showarchive = $this->GetPreference('default_showarchive',0);
$sortorder = $this->GetPreference('default_sortorder','desc');
$sortby = $this->GetPreference('default_sortby','cgblog_date');
$pagelimit = $this->GetPreference('default_pagelimit',100000);

{
  // if the user is logged in, and a member of the proper group... and the showdraft param is supplied
  // allow showing draft articles.
  $feu = cge_utils::get_module('FrontEndUsers');
  $gid = $this->GetPreference('fesubmit_draftviewers',-1);
  if( $gid > 0 ) {
    if( $feu->MemberOfGroup($feu->LoggedInId(),$gid) ) {
      if( isset($params['showdraft']) && $params['showdraft'] ) {
	$showdraft = 1;
      }
    }
  }
}

$cache_id = '|cgb'.md5(serialize($params).$showdraft);
$compile_id = '';

// Display template
$template = 'summary'.$this->GetPreference('current_summary_template');
if (isset($params['summarytemplate'])) $template = 'summary'.$params['summarytemplate'];

if( !$smarty->isCached($this->GetDatabaseResource($template),$cache_id,$compile_id) ) {
  if( isset($params['showall']) && $params['showall'] ) $showall = 1;

  $detailpage = cgblog_utils::get_detailpage($returnid,$params);
  $entryarray = array();
  $parms = array();
  $joins = array();
  $where = array();
  $query1 = "SELECT DISTINCT mn.* FROM ". cms_db_prefix() . "module_cgblog mn"; 
  $query2 = "SELECT count(DISTINCT mn.cgblog_id) as count FROM " . cms_db_prefix() . "module_cgblog mn";
  if( !$showall ) {
    $where[] = "status = ?";
    if( $showdraft ) {
      $parms[] = 'draft';
    }
    else {
      $parms[] = 'published';
    }
  }
  if( isset($params['sortby']) ) $sortby = trim($params['sortby']);
  if( isset($params['sortasc']) ) {
    $tmp = cge_utils::to_bool($params['sortasc']);
    if( $tmp ) {
      $sortorder = 'asc';
    }
    else {
      $sortorder = 'desc';
    }
  }

  if( isset($params['year']) ) {
    $smonth = 1;
    $emonth = 12;
    $sday = 1;
    $eday = 31;

    if( isset($params['month']) ) {
      $smonth = (int)$params['month'];
      $emonth = (int)$params['month'];
      $eday = date('t',mktime(0,0,0,$smonth,$sday,$params['year']));
    }
    $t1 = mktime(0,0,0,$smonth,$sday,$params['year']);
    $t1_d = $db->DbTimeStamp($t1);
    $t2 = mktime(23,59,0,$emonth,$eday,$params['year']);
    $t2_d = $db->DbTimeStamp($t2);
    $where[] = "(mn.start_time BETWEEN $t1_d and $t2_d)";
  }
  else {
    $where[] = "(".$db->IfNull('start_time',$db->DBTimeStamp(1))." < NOW())";
  }

  if (isset($params['author']) && $params['author'] != '' ) {
    // filter by username.
    $feu = cge_utils::get_module('FrontEndUsers');
    if( !$feu ) return false; // no feu modules, therefore no results.

    $user = cms_html_entity_decode(trim($params['author']));
    $users = explode(',',$user);
    for( $i = 0; $i < count($users); $i++ ) {
      $users[$i] = "'".trim($users[$i])."'";
    }
    $tmp = implode(',',$users);
    // make sure we're exluding expired users.
    $query = 'SELECT username FROM '.cms_db_prefix().'module_feusers_users
            WHERE username IN ('.$tmp.') AND expires > NOW()';
    $tmp = $db->GetCol($query);
    if( !is_array($tmp) ) return; // get outa here... no matching users.

    for( $i = 0; $i < count($tmp); $i++ ) {
      $tmp[$i] = "'".trim($tmp[$i])."'";
    }
    $where[] = "mn.author IN (".implode(',',$tmp).')';
  }

  if( isset($params['admin_user']) && $params['admin_user'] != '' ) {
    $user = cms_html_entity_decode(trim($params['admin_user']));
    $users = explode(',',$user);
    for( $i = 0; $i < count($users); $i++ ) {
      $users[$i] = "'".trim($users[$i])."'";
    }
    $tmp = implode(',',$users);

    // make sure we're exluding expired users.
    $query = 'SELECT username FROM '.cms_db_prefix().'users 
            WHERE ((username IN ('.$tmp.'))
            OR  (email IN ('.$tmp.')))
            AND active = 1';
    $tmp = $db->GetCol($query);
    if( !is_array($tmp) ) return; // get outa here... no matching users.

    for( $i = 0; $i < count($tmp); $i++ ) {
      $val = $tmp[$i];
      $tmp[$i] = "'".trim($val)."'";
    }
    $where[] = "mn.author IN (".implode(',',$tmp).')';
  }

  if (isset($params["category"]) && $params["category"] != '') {
    // only show results from these (comma separated) category names.
    $category = cms_html_entity_decode(trim($params['category']));
    $categories = explode(',', $category);
    for( $i = 0; $i < count($categories); $i++ ) {
      $categories[$i] = "'".trim($categories[$i])."'";
    }
    $tmp = implode(",",$categories);
    $query = 'SELECT id FROM '.cms_db_prefix().'module_cgblog_categories WHERE name IN ('.$tmp.')';
    $tmp = $db->GetArray($query);

    if( !is_array($tmp) ) return; // get outa here... no matching categories.

    $tmp2 = cge_array::extract_field($tmp,'id');

    $joins[] = "LEFT OUTER JOIN ".cms_db_prefix().'module_cgblog_blog_categories bc ON mn.cgblog_id = bc.blog_id';
    $where[] = "bc.category_id IN (".implode(',',$tmp2).')';
  }
  else if( isset($params['notcategory']) ) {
    // do not show any results from these (comma separated) category names.
    $ncategory = cms_html_entity_decode(trim($params['notcategory']));
    $ncategories = explode(',', $ncategory);
    for( $i = 0; $i < count($ncategories); $i++ ) {
      $ncategories[$i] = "'".trim($ncategories[$i])."'";
    }
    $tmp = implode(",",$ncategories);
    $query = 'SELECT id FROM '.cms_db_prefix().'module_cgblog_categories WHERE name NOT IN ('.$tmp.')';
    $tmp = $db->GetArray($query);

    if( !is_array($tmp) ) return; // get outa here... no matching categories.

    $tmp2 = cge_array::extract_field($tmp,'id');

    $joins[] = "LEFT OUTER JOIN ".cms_db_prefix().'module_cgblog_blog_categories bc ON mn.cgblog_id = bc.blog_id';
    $where[] = "bc.category_id IN (".implode(',',$tmp2).')';
  }
  else if( isset($params['category_id']) ) {
    // a single category passed in.
    $query = 'SELECT name FROM '.cms_db_prefix().'module_cgblog_categories WHERE id = ?';
    $tmp = $db->GetOne($query,array((int)$params['category_id']));
    if( $tmp ) $smarty->assign('cgblog_category',$tmp);

    $joins[] = "LEFT OUTER JOIN ".cms_db_prefix().'module_cgblog_blog_categories bc ON mn.cgblog_id = bc.blog_id';
    $where[] = "bc.category_id = ?";
    $parms[] = (int)$params['category_id'];
  }
  if( isset($params['showarchive']) && $params['showarchive'] ) $showarchive = 1;
  if( !$showall ) {
    if ($showarchive) {
      // get articles that are expired
      $where[] = "(end_time < NOW())";
    }
    else {
      // get articles with either no expiry, or an end time greater than now
      $where[] = "((".$db->IfNull('end_time',$db->DBTimeStamp(1))." = ".$db->DBTimeStamp(1).") OR (end_time > NOW()))";
    }
  }


  //
  // final query assemby
  //
  if( count($joins) ) {
    $query1 .= " ".implode(" ",$joins);
    $query2 .= " ".implode(" ",$joins);
  }
  if( count($where) ) {
    $query1 .= " WHERE ".implode(" AND ",$where);
    $query2 .= " WHERE ".implode(" AND ",$where);
  }
  $query1 .= " ";
  $sortrandom = false;

  // sortby.
  switch( $sortby ) {
  case 'cgblog_category':
    $query1 .= "ORDER BY 'long_name', 'cgblog_date' ";
    break;

  case 'random':
    $query1 .= ' ORDER BY RAND() ';
    break;

  case 'cgblog_date':
  case 'cgblog_title':
  case 'summary':
  case 'start_time':
  case 'end_time':
  case 'cgblog_extra':
    $query1 .= "ORDER BY mn." . str_replace("'", '', str_replace(';', '', $db->qstr($sortby))) . " ";
    break;

  default:
    $query1 .= 'ORDER BY cgblog_date ';
    break;
  }
  $query1 .= $sortorder;

  if( isset( $params['pagelimit'] ) ) {
    $pagelimit = intval($params['pagelimit']);
  }
  else if( isset( $params['number'] ) ) {
    $pagelimit = intval($params['number']);
  }
		
  // Get the number of rows (so we can determine the numer of pages)
  $pagecount = -1;
  $startelement = 0;
  $pagenumber = 1;
  {
    // get the total number of items that match the query
    // and determine a number of pages
    $row2 = $db->GetRow($query2,$parms);
    $count = intval($row2['count']);
    if( isset( $params['start'] ) ) {
      $count -= (int)$params['start'];
    }
    $pagecount = (int)($count / $pagelimit);
    if( ($count % $pagelimit) != 0 ) $pagecount++;
  }
  if( isset( $params['pagenumber'] ) && $params['pagenumber'] != '' ) {
    // if given a page number, determine a start element
    $pagenumber = (int)$params['pagenumber'];
    $startelement = ($pagenumber-1) * $pagelimit;
  }
  if( isset( $params['start'] ) ) $startelement = $startelement + (int)$params['start'];

  // Assign some pagination variables to smarty
  if( $pagenumber == 1 ) {
    $smarty->assign('prevpage',$this->Lang('prevpage'));
    $smarty->assign('firstpage',$this->Lang('firstpage'));
  }
  else {
    $params['pagenumber']=$pagenumber-1;
    $smarty->assign('prevpage',$this->CreateFrontendLink($id,$returnid,'default',$this->Lang('prevpage'),$params));
    $smarty->assign('prevurl',$this->CreateFrontendLink($id,$returnid,'default','',$params, '', true));
    $params['pagenumber']=1;
    $smarty->assign('firstpage',$this->CreateFrontendLink($id,$returnid,'default',$this->Lang('firstpage'),$params));
    $smarty->assign('firsturl',$this->CreateFrontendLink($id,$returnid,'default','',$params, '', true));
  }
    
  if( $pagenumber >= $pagecount ) {
    $smarty->assign('nextpage',$this->Lang('nextpage'));
    $smarty->assign('lastpage',$this->Lang('lastpage'));
  }
  else {
    $params['pagenumber']=$pagenumber+1;
    $smarty->assign('nextpage',$this->CreateFrontendLink($id,$returnid,'default',$this->Lang('nextpage'),$params));
    $smarty->assign('nexturl',$this->CreateFrontendLink($id,$returnid,'default','',$params, '', true));
    $params['pagenumber']=$pagecount;
    $smarty->assign('lastpage',$this->CreateFrontendLink($id,$returnid,'default',$this->Lang('lastpage'),$params));
    $smarty->assign('lasturl',$this->CreateFrontendLink($id,$returnid,'default','',$params, '', true));
  }
  $smarty->assign('pagenumber',$pagenumber);
  $smarty->assign('pagecount',$pagecount);
  $smarty->assign('oftext',$this->Lang('prompt_of'));
  $smarty->assign('pagetext',$this->Lang('prompt_page'));

  //$query1 .= " LIMIT $pagelimit OFFSET $startelement";
  $dbresult = '';
  $dbresult = $db->SelectLimit( $query1,$pagelimit,$startelement,$parms);
  while ($dbresult && $row = $dbresult->FetchRow()) {
    $onerow = new stdClass();

    $onerow->author = $row['author'];
    $onerow->id = $row['cgblog_id'];
    $onerow->title = $row['cgblog_title'];
    $onerow->content = $row['cgblog_data'];
    $onerow->summary = (trim($row['summary'])!='<br/>'?$row['summary']:'');
    $onerow->postdate = $row['cgblog_date'];
    $onerow->url = $row['url'];
    if( FALSE == empty($row['cgblog_extra']) ) $onerow->extra = $row['cgblog_extra'];
    $onerow->postdate = $row['cgblog_date'];
    $onerow->startdate = $row['start_time'];
    $onerow->enddate = $row['end_time'];

    //
    // Handle categories
    //
    {
      $query = 'SELECT A.category_id,B.name 
              FROM '.cms_db_prefix().'module_cgblog_blog_categories A
              LEFT JOIN '.cms_db_prefix().'module_cgblog_categories B
              ON A.category_id = B.id
              WHERE A.blog_id = ?';
      $tmp = $db->GetArray($query,array($row['cgblog_id']));
      if( is_array($tmp) ) $onerow->categories = $tmp;
    }

    //
    // Handle the custom fields
    //
    $query3 = 'SELECT A.value,B.id,B.name,B.type FROM '.cms_db_prefix().'module_cgblog_fieldvals A, '.cms_db_prefix().'module_cgblog_fielddefs B WHERE A.fielddef_id = B.id AND B.public = 1 AND A.cgblog_id = ? ORDER BY B.item_order';
    $dbr3 = $db->Execute($query3,array($row['cgblog_id']));
    $fields = array();
    $fieldsbyname = array();
    while( $dbr3 && ($row3 = $dbr3->FetchRow()) ) {
      $alias = str_replace('-','_',munge_string_to_url($row3['name']));

      $obj = new StdClass();
      foreach( $row3 as $k => $v ) {
	$obj->$k = $v;
      }
      $fields[] = $obj;
      $fieldsbyname[$row3['name']] = $obj;
      if( !isset($onerow->$alias) ) $onerow->$alias = $row3['value']; // deprecated.
    }
    $onerow->fieldsbyname = $fieldsbyname;
    $onerow->fields = $fieldsbyname;
    $onerow->file_location = $config['uploads_url'].'/cgblog/id'.$row['cgblog_id'];

    $sendtodetail = array('articleid'=>$row['cgblog_id']);
    if (isset($params['detailtemplate'])) $sendtodetail['detailtemplate'] = $params['detailtemplate'];
    $prettyurl = $onerow->url;
    if( $prettyurl == '' ) {
      $aliased_title = munge_string_to_url($row['cgblog_title']);
      if( $this->GetPreference('default_detailpage',-1) != -1 && !isset($params['detailpage']) ) {
	$prettyurl = $this->GetPreference('urlprefix','cgblog').'/'.$row['cgblog_id']."/$aliased_title";
      }
      else {
	$prettyurl = $this->GetPreference('urlprefix','cgblog').'/'.$row['cgblog_id'].'/'.$detailpage."/$aliased_title";
      }
    }

    $onerow->detail_url = $this->CreateLink($id, 'detail', $detailpage, '', $sendtodetail,'', true, false, '', true, $prettyurl);

    $entryarray[]= $onerow;
  }
  $smarty->assign('itemcount', count($entryarray));
  $smarty->assign_by_ref('items', $entryarray);
  $smarty->assign('category_label', $this->Lang('category_label'));
  $smarty->assign('author_label', $this->Lang('author_label'));

  $statusdropdown = array();
  $statusdropdown[$this->Lang('draft')] = 'draft';
  $statusdropdown[$this->Lang('published')] = 'published';
  $statusdropdown = array_flip($statusdropdown);
  $smarty->assign('statusopts',$statusdropdown);

  foreach( $params as $key => $value ) {
    if( $key == 'mact' || $key == 'action' ) continue;

    $smarty->assign('param_'.$key,$value);
  }
}

// Display template
echo $smarty->fetch($this->GetDatabaseResource($template),$cache_id,$compile_id);
# vim:ts=4 sw=4 noet
?>
